// 设置系统状态管理
// 管理所有应用设置的状态和操作

import { create } from 'zustand';
import { subscribeWithSelector } from 'zustand/middleware';
import { persist } from 'zustand/middleware';
import {
  SettingsConfig,
  SettingsCategory,
  BaseSetting,
  SettingChangeEvent,
  SettingValidationResult,
  SettingSearchResult,
  SettingsExport,
  EditorSettings,
  AppearanceSettings,
  KeyboardSettings,
  FileSettings,
  ExtensionSettings,
  AdvancedSettings
} from '../types/settings';
import { SettingsValidator } from '../services/settingsValidator';
import { SettingsSearchService } from '../services/settingsSearch';
import { SettingsImportExport } from '../utils/settingsImportExport';

// 默认设置配置
const defaultSettings: SettingsConfig = {
  editor: {
    fontSize: 14,
    fontFamily: 'Consolas, "Courier New", monospace',
    lineHeight: 1.5,
    tabSize: 2,
    insertSpaces: true,
    wordWrap: false,
    showLineNumbers: true,
    showMinimap: true,
    showWhitespace: false,
    showIndentGuides: true,
    autoSave: true,
    autoSaveDelay: 1000,
    formatOnSave: false,
    formatOnPaste: false,
    trimTrailingWhitespace: true,
    insertFinalNewline: true,
    quickSuggestions: true,
    suggestOnTriggerCharacters: true,
    acceptSuggestionOnEnter: true,
    snippetSuggestions: true,
    folding: true,
    foldingStrategy: 'auto',
    showFoldingControls: 'mouseover',
    cursorBlinking: 'blink',
    cursorStyle: 'line',
    multiCursorModifier: 'ctrlCmd',
    smoothScrolling: true,
    mouseWheelScrollSensitivity: 1,
    fastScrollSensitivity: 5
  },
  appearance: {
    theme: 'auto',
    followSystemTheme: true,
    accentColor: '#007ACC',
    backgroundColor: '#1E1E1E',
    foregroundColor: '#CCCCCC',
    sidebarPosition: 'left',
    panelPosition: 'bottom',
    showActivityBar: true,
    showStatusBar: true,
    showToolbar: true,
    uiFontFamily: 'system-ui, -apple-system, sans-serif',
    uiFontSize: 13,
    iconTheme: 'default',
    showFileIcons: true,
    showFolderIcons: true,
    enableAnimations: true,
    animationDuration: 200,
    windowOpacity: 1.0,
    sidebarOpacity: 1.0
  },
  keyboard: {
    shortcuts: {},
    enableGlobalShortcuts: true,
    customShortcuts: {},
    conflictResolution: 'warn'
  },
  files: {
    associations: {},
    defaultEncoding: 'utf8',
    autoGuessEncoding: true,
    eol: 'auto',
    watcherExclude: ['**/node_modules/**', '**/target/**', '**/.git/**'],
    usePolling: false,
    autoSave: 'afterDelay',
    autoSaveDelay: 1000,
    enableBackup: true,
    backupLocation: '.vscode/backups',
    maxBackupFiles: 10
  },
  extensions: {
    enabledExtensions: [],
    disabledExtensions: [],
    autoUpdate: true,
    checkUpdateInterval: 24,
    allowPrerelease: false
  },
  advanced: {
    maxMemoryUsage: 1024,
    enableGPUAcceleration: true,
    enableDebugMode: false,
    logLevel: 'info',
    proxySettings: {
      enabled: false,
      host: '',
      port: 8080
    },
    experimentalFeatures: []
  }
};

// 设置状态接口
export interface SettingsState {
  // 当前设置
  settings: SettingsConfig;
  
  // 设置历史
  changeHistory: SettingChangeEvent[];
  
  // 搜索状态
  searchQuery: string;
  searchResults: SettingSearchResult[];
  
  // UI状态
  isSettingsDialogOpen: boolean;
  activeCategory: SettingsCategory;
  isDirty: boolean;
  
  // 操作方法
  // 基础设置操作
  getSetting: <T = any>(settingId: string) => T | undefined;
  setSetting: (settingId: string, value: any) => void;
  resetSetting: (settingId: string) => void;
  resetCategory: (category: SettingsCategory) => void;
  resetAllSettings: () => void;
  
  // 批量操作
  updateSettings: (updates: Partial<SettingsConfig>) => void;
  
  // 验证
  validateSetting: (settingId: string, value: any) => SettingValidationResult;
  validateAllSettings: () => Record<string, SettingValidationResult>;
  
  // 搜索
  searchSettings: (query: string) => void;
  clearSearch: () => void;
  
  // 导入导出
  exportSettings: () => SettingsExport;
  importSettings: (data: SettingsExport) => Promise<boolean>;
  
  // UI控制
  openSettingsDialog: (category?: SettingsCategory) => void;
  closeSettingsDialog: () => void;
  setActiveCategory: (category: SettingsCategory) => void;
  
  // 历史记录
  getChangeHistory: () => SettingChangeEvent[];
  clearHistory: () => void;
  
  // 监听器
  onSettingChange: (callback: (event: SettingChangeEvent) => void) => () => void;
}

// 创建设置Store
export const useSettingsStore = create<SettingsState>()(
  subscribeWithSelector(
    persist(
      (set, get): SettingsState => ({
        settings: defaultSettings,
        changeHistory: [],
        searchQuery: '',
        searchResults: [],
        isSettingsDialogOpen: false,
        activeCategory: SettingsCategory.Editor,
        isDirty: false,

        getSetting: <T = any>(settingId: string): T | undefined => {
          const state = get();
          const parts = settingId.split('.');
          let current: any = state.settings;
          
          for (const part of parts) {
            if (current && typeof current === 'object' && part in current) {
              current = current[part];
            } else {
              return undefined;
            }
          }
          
          return current as T;
        },

        setSetting: (settingId: string, value: any) => {
          const state = get();
          const oldValue = state.getSetting(settingId);
          
          if (oldValue === value) return;
          
          const parts = settingId.split('.');
          const category = parts[0] as SettingsCategory;
          
          set((state) => {
            const newSettings = { ...state.settings };
            let current: any = newSettings;
            
            // 导航到设置项的父对象
            for (let i = 0; i < parts.length - 1; i++) {
              if (!(parts[i] in current)) {
                current[parts[i]] = {};
              }
              current = current[parts[i]];
            }
            
            // 设置值
            current[parts[parts.length - 1]] = value;
            
            // 创建更改事件
            const changeEvent: SettingChangeEvent = {
              settingId,
              oldValue,
              newValue: value,
              category,
              timestamp: Date.now()
            };
            
            return {
              settings: newSettings,
              changeHistory: [...state.changeHistory, changeEvent],
              isDirty: true
            };
          });
        },

        resetSetting: (settingId: string) => {
          const parts = settingId.split('.');
          let defaultValue: any = defaultSettings;
          
          for (const part of parts) {
            if (defaultValue && typeof defaultValue === 'object' && part in defaultValue) {
              defaultValue = defaultValue[part];
            } else {
              return;
            }
          }
          
          get().setSetting(settingId, defaultValue);
        },

        resetCategory: (category: SettingsCategory) => {
          set((state) => ({
            settings: {
              ...state.settings,
              [category]: defaultSettings[category]
            },
            isDirty: true
          }));
        },

        resetAllSettings: () => {
          set({
            settings: defaultSettings,
            isDirty: true
          });
        },

        updateSettings: (updates: Partial<SettingsConfig>) => {
          set((state) => ({
            settings: {
              ...state.settings,
              ...updates
            },
            isDirty: true
          }));
        },

        validateSetting: (settingId: string, value: any): SettingValidationResult => {
          // 创建临时设置对象用于验证
          const tempSetting: BaseSetting = {
            id: settingId,
            name: settingId,
            description: '',
            category: SettingsCategory.Advanced,
            type: 'string' as any,
            defaultValue: null,
            currentValue: value
          };

          return SettingsValidator.validateSetting(tempSetting, value);
        },

        validateAllSettings: (): Record<string, SettingValidationResult> => {
          const state = get();
          const results: Record<string, SettingValidationResult> = {};

          // 验证所有设置分类
          Object.entries(state.settings).forEach(([category, categorySettings]) => {
            Object.entries(categorySettings as any).forEach(([key, value]) => {
              const settingId = `${category}.${key}`;
              results[settingId] = state.validateSetting(settingId, value);
            });
          });

          return results;
        },

        searchSettings: (query: string) => {
          set({ searchQuery: query });
          const results = SettingsSearchService.searchSettings(query);
          set({ searchResults: results });
        },

        clearSearch: () => {
          set({
            searchQuery: '',
            searchResults: []
          });
        },

        exportSettings: (): SettingsExport => {
          const state = get();
          return {
            version: '1.0.0',
            timestamp: Date.now(),
            settings: state.settings,
            metadata: {
              appVersion: '1.0.0',
              platform: navigator.platform,
              exportedBy: 'CodeGraph Editor'
            }
          };
        },

        importSettings: async (data: SettingsExport): Promise<boolean> => {
          try {
            // 验证导入数据
            const validation = SettingsImportExport.validateSettingsValues(data.settings);
            if (!validation.isValid) {
              console.error('Invalid settings data:', validation.errors);
              return false;
            }

            // 合并设置
            const currentSettings = get().settings;
            const mergedSettings = SettingsImportExport.mergeSettings(currentSettings, data.settings);

            get().updateSettings(mergedSettings);
            return true;
          } catch (error) {
            console.error('Failed to import settings:', error);
            return false;
          }
        },

        openSettingsDialog: (category?: SettingsCategory) => {
          set({
            isSettingsDialogOpen: true,
            activeCategory: category || SettingsCategory.Editor
          });
        },

        closeSettingsDialog: () => {
          set({
            isSettingsDialogOpen: false,
            isDirty: false
          });
        },

        setActiveCategory: (category: SettingsCategory) => {
          set({ activeCategory: category });
        },

        getChangeHistory: () => {
          return get().changeHistory;
        },

        clearHistory: () => {
          set({ changeHistory: [] });
        },

        onSettingChange: (callback: (event: SettingChangeEvent) => void): (() => void) => {
          return useSettingsStore.subscribe(
            (state: SettingsState) => state.changeHistory,
            (history: SettingChangeEvent[], prevHistory: SettingChangeEvent[]) => {
              if (history.length > prevHistory.length) {
                const latestChange = history[history.length - 1];
                callback(latestChange);
              }
            }
          );
        }
      }),
      {
        name: 'codegraph-settings-store',
        version: 1,
        partialize: (state) => ({
          settings: state.settings,
          changeHistory: state.changeHistory.slice(-100) // 只保留最近100条历史
        })
      }
    )
  )
);
